package cn.cocho.android.mc.activity;

import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;

import cn.cocho.android.mc.comp.dialog.ProgressDialog;
import cn.cocho.android.mc.log.LoggerUtils;

/**
 * 异步加载数据包含提示框
 * 
 * @author HAIKANG SONG
 * @2013年11月18日 @上午10:36:51
 */
public abstract class AsyncDialog<Params, Progress, Result> {
	
	private CharSequence title;//提示框的标题
	private CharSequence message;//提示框的内容
	private ProgressDialog dialog;
	AsyncTask<Params, Progress, Result> task;
	
	public AsyncDialog(String title, String message) {
		this.title = title;
		this.message = message;
		initDataWithSync();
	}
	
	public AsyncDialog() {
		this.title = "提示";
		this.message = "数据加载中...";
		initDataWithSync();
	}

	/**
	 * 异步初始化数据
	 * 
	 * @author HAIKANG SONG
	 */
	@SuppressWarnings("unchecked")
	public void initDataWithSync() {
		dialog = new ProgressDialog();
		dialog.setTitle(title);
		dialog.setMessage(message);
		// 设置dialog 是否可以按退回按键取消
		dialog.setCancelable(false);

		task = new AsyncTask<Params, Progress, Result>() {
			@Override
			protected Result doInBackground(Params... params) {
				try {
					return initDatas(params);
				} catch (Exception e) {
					LoggerUtils.error(e);
				}
				return null;
			}

			@Override
			protected void onPostExecute(Result result) {
				dialog.dismiss();
				initDatasAfter(result);
			}
		}.execute();

		dialog.show();
		dialog.getCancelButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				task.cancel(true);
				initDatasAfter(null);
			}
		});
	}
	

	public CharSequence getTitle() {
		return title;
	}

	public void setTitle(CharSequence title) {
		dialog.setTitle(title);
		this.title = title;
	}

	public CharSequence getMessage() {
		return message;
	}

	public void setMessage(CharSequence message) {
		dialog.setMessage(message);
		this.message = message;
	}

	public ProgressDialog getDialog() {
		return dialog;
	}

	public void setDialog(ProgressDialog dialog) {
		this.dialog = dialog;
	}

	/**
	 * 初始化数据
	 * @param params 初始化数据所需的参数
	 * @return 返回为指定的result类型
	 * @author HAIKANG SONG
	 */
	public abstract Result initDatas(Params... params);

	/**
	 * 数据初始化之后调用
	 * @param result 指定的result类型的结果或null
	 * @author HAIKANG SONG
	 */
	public abstract void initDatasAfter(Result result);
	
	
	

}
